<template>
  <div>
    <a-modal title="创建多渠道配送单" :visible="visible" @before-open="open" @ok.stop="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="800px" :mask-closable="false">
      <div class="title" v-if="step < 3">
        <div :class="['title-item', step == 1 ? 'first' : '']"> 获取亚马逊FBA订单</div>
        <div :class="['title-item', step == 2 ? 'second' : '']"> 确认关联</div>
      </div>

      <div v-if="step == 1">
        <div class="item-con">
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">站点：</div>
              <div class="fl">{{ getMarkplaceName() }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">店铺：</div>
              <div class="fl">{{ $extract(info, 'customOrderInfo.shopName') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">买家电话：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.phoneNumber') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">买家邮箱：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.email') ? $extract(info, 'customOrderInfo.address.email') : '--' }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">国家：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.country') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">收件人：</div>
              <div class="fl">{{ $extract(info, 'customOrderInfo.address.userName') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">省/州：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.stateOrRegion') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">城市：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.city') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">邮编：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.postalCode') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">详细地址：</div>
              <div class="fl label-value">{{ $extract(info, 'customOrderInfo.address.address') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">商家订单号：</div>
              <div class="fl label-value">{{ initNum }} </div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">配送速度：</div>
              <div class="fl label-value">
                <a-radio-group v-model="speed">
                  <a-radio value="Standard">标准</a-radio>
                  <a-radio value="Expedited">加急</a-radio>
                  <a-radio value="Priority">优先</a-radio>
                </a-radio-group>
              </div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl" style="width: 100%">
              <div class="fl label-text">装箱备注：</div>
              <div class="fl label-value">
                <a-textarea v-model="remark" placeholder="请输入" allow-clear />
              </div>
            </div>
          </div>
        </div>

        <div class="table">
          <a-table size="mini" class="table-single-line" :data="list" :pagination="false" :scroll="{ y: '200px' }">
            <template #columns>
              <a-table-column title="图片" :width="60" #cell="{ record }">
                <a-image :src="record.productPic" :width="40" :height="40" />
              </a-table-column>
              <a-table-column title="SKU" :width="120" #cell="{ record }">{{ record.productSku }}</a-table-column>
              <a-table-column title="数量" :width="40" #cell="{ record }">{{ record.qtyShipped }}</a-table-column>
              <a-table-column title="MSKU" :width="140" #cell="{ record }">
                <!-- <a-input placeholder="请输入" v-model="record.fnsku"></a-input> -->
                <a-select v-model="record.msku" allow-search>
                  <a-option v-for="item of record.onlineProductList" :label="item.msku" :value="item.msku"></a-option>
                </a-select>
              </a-table-column>
              <a-table-column title="FNSKU" :width="140" #cell="{ record }">{{ record.onlineFnsku }} </a-table-column>
              <a-table-column title="可用库存" :width="60" #cell="{ record }">{{ record.residualInventory }}</a-table-column>
            </template>
          </a-table>
        </div>
      </div>

      <div v-if="step == 2">
        <div class="item-con">
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">站点：</div>
              <div class="fl">{{ getMarkplaceName() }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">店铺：</div>
              <div class="fl">{{ $extract(submitInfo, 'shopName') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">买家电话：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.phoneNumber') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">买家邮箱：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.email') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">国家：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.country') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">收件人：</div>
              <div class="fl">{{ $extract(submitInfo, 'address.userName') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">省/州：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.stateOrRegion') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">城市：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.city') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">邮编：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.postalCode') }}</div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">详细地址：</div>
              <div class="fl label-value">{{ $extract(submitInfo, 'address.address') }}</div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">商家订单号：</div>
              <div class="fl label-value">{{ submitInfo.sellerFulfillmentOrderId }} </div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">配送速度：</div>
              <div class="fl label-value"> {{ enumSpeed() }} </div>
            </div>
          </div>
          <div class="clearfix item">
            <div class="clearfix fl">
              <div class="fl label-text">装箱备注：</div>
              <div class="fl label-value"> {{ submitInfo.remark }} </div>
            </div>
            <div class="clearfix fl">
              <div class="fl label-text">预计配送详情：</div>
              <div class="fl label-value">
                <div>
                  <span>配送重量:</span>
                  <span class="ml10">{{ $extract(submitInfo, 'getFulfillmentPreviewResult.weight.value') }}</span>
                </div>
                <div>
                  <span>配送日期:</span>
                  <span class="ml10">{{ $extract(submitInfo, 'getFulfillmentPreviewResult.fulfillmentPreviewShipment.latestShipDate') }}</span>
                </div>
                <div>
                  <span>送达日期:</span>
                  <span class="ml10">{{ $extract(submitInfo, 'getFulfillmentPreviewResult.fulfillmentPreviewShipment.latestArrivalDate') }}</span>
                </div>
                <div>
                  <span>订单总额:</span>
                  <span class="ml10">{{ orderMoney() }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="table">
          <a-table size="mini" class="table-single-line" :data="submitInfo.packItemList || []" :pagination="false" :scroll="{ y: '200px' }">
            <template #columns>
              <a-table-column title="图片" :width="60" #cell="{ record }">
                <a-image :src="record.productPic" :width="40" :height="40" />
              </a-table-column>
              <a-table-column title="SKU" :width="120" #cell="{ record }">{{ record.productSku }}</a-table-column>
              <a-table-column title="数量" :width="40" #cell="{ record }">{{ record.qtyShipped }}</a-table-column>
              <a-table-column title="MSKU" :width="140" #cell="{ record }">{{ record.msku }}</a-table-column>
              <a-table-column title="FNSKU" :width="140" #cell="{ record }"> {{ record.fnsku }} </a-table-column>
              <a-table-column title="可用库存" :width="60" #cell="{ record }">{{ record.amtAvailableStock }}</a-table-column>
            </template>
          </a-table>
        </div>
      </div>

      <template #footer>
        <div v-if="step == 1">
          <a-button class="gray-outline" @click="handleCancel">取消</a-button>
          <a-button type="primary" style="margin-left: 10px" :loading="nextLoading" @click="next">下一步</a-button>
        </div>
        <div v-if="step == 2">
          <a-button class="gray-outline" @click="handleCancel">取消</a-button>
          <a-button class="gray-outline ml10" @click="pre">上一步</a-button>
          <a-button type="primary" style="margin-left: 10px" :loading="submitLoading" @click="submit">确认下单</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { findShopPageByParam } from '@/api/system'
  import { findShopMarketByParam, getFulfillmentPreview, createFulfillmentOrder, getInventorySummaries } from '@/api/order'
  import { getAmzProductSale } from '@/api/publish'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const data: any = reactive({
        step: 1,
        speed: 'Standard',
        submitInfo: {},
        remark: '感谢您的订购！',
        list: [],
        markplaceList: [],
        initNum: '',
        nextLoading: false,
        submitLoading: false,
      })

      const open = () => {
        data.step = 1
        getMarketList()
        initNumber()
        setList()
      }
      const handleOk = () => {}
      const handleCancel = () => {
        data.step = 1
        data.submitLoading = false
        data.nextLoading = false
        visible.value = false
      }

      const pre = () => {
        data.step = 1
      }
      const next = async () => {
        if (!data.remark) {
          return Message.error('请输入备注')
        }
        let params: any = {
          address: props.info.customOrderInfo.address,
          marketplaceId: props.info.marketplaceId,
          orderId: props.info.orderId,
          packageId: props.info.id,
          remark: data.remark,
          shippingSpeedCategory: data.speed,
          sellerId: props.info.sellerId,
          shopName: props.info.customOrderInfo.shopName,
          sellerFulfillmentOrderId: data.initNum,
          packageNumber: props.info.packageNumber,
          isUseVirtual: true,
          packItemList: [],
        }

        data.list.forEach((e: any) => {
          let obj = {
            amtAvailableStock: 0,
            fnsku: e.onlineFnsku || '',
            msku: e.msku,
            packItemId: e.orderPackageId,
            productPic: e.productPic,
            productSku: e.productSku,
            quantity: e.qtyShipped,
          }
          params.packItemList.push(obj)
        })

        data.nextLoading = true
        try {
          const res: any = await getFulfillmentPreview(params)
          if (res) {
            data.step = 2
            data.submitInfo = res?.data || {}
          }
          data.nextLoading = false
        } catch (error) {
          data.nextLoading = false
        }
      }

      const submit = async () => {
        try {
          data.submitLoading = true
          const res: any = await createFulfillmentOrder(data.submitInfo)
          data.remark = '感谢您的订购！'
          Message.success('创建多渠道订单成功')
          data.submitLoading = false
          visible.value = false
          data.step = 1
          emit('save')
        } catch (error) {
          data.submitLoading = false
        }
      }

      const getImage = (item: any) => {
        if (item.isCustom) {
          let arr = item.customPics ? item.customPics.split(',') : []
          return arr[0]
        } else {
          return item.productPic
        }
      }

      const initNumber = () => {
        let orderNum = props.info.customOrderInfo.platformOrderNumber
        let randomNumber = Math.floor(Math.random() * 100000)
        let fiveDigitNumber = randomNumber.toString().padStart(5, '0')
        data.initNum = `${orderNum}-${fiveDigitNumber}`
      }

      const getMarketList = async () => {
        const res = await findShopMarketByParam()
        data.markplaceList = res?.data || []
      }

      const getMarkplaceName = () => {
        let marketplaceId = props.info.marketplaceId
        let obj = data.markplaceList.find((e: any) => e.marketplaceId == marketplaceId)
        return obj ? obj.marketplaceName : '--'
      }

      const setList = async () => {
        data.list = _.cloneDeep(props.info).packageItemList
        amazonProductList()
        let params = {
          marketplaceId: props.info?.marketplaceId || '',
          sellerId: props.info?.sellerId || '',
          sellerSkuList: data.list.map((e) => e.msku).join(','),
        }
        const res: any = await getInventorySummaries(params)
        let numList = res?.data?.payload?.inventorySummaries || []

        data.list.map((e) => {
          let item: any = numList.find((el) => el.sellerSku == e.msku)
          if (item) e.residualInventory = item.inventoryDetails && item.inventoryDetails.fulfillableQuantity ? item.inventoryDetails.fulfillableQuantity : ''
        })
      }

      const amazonProductList = async () => {
        let skuList = data.list.map((e: any) => (e.productSku ? e.productSku : ''))
        let params = {
          pageSize: 999999,
          marketplaceIdList: props.info.customOrderInfo.marketplaceId,
          sellerIdList: props.info.customOrderInfo.sellerId,
          skuList: skuList.join(','),
          isChild: true,
        }
        const res: any = await getAmzProductSale(params)

        data.list.forEach((e: any) => {
          let arr = res.data.records.filter((el: any) => el.product.sku == e.productSku) || []
          e.onlineFnsku = arr[0] ? arr[0].fnsku : ''
          e.onlineMsku = arr[0] ? arr[0].msku : ''
          e.onlineProductList = arr
        })
      }

      const enumSpeed = () => {
        let text = ''
        if (data.submitInfo.shippingSpeedCategory == 'Standard') {
          text = '标准'
        } else if (data.submitInfo.shippingSpeedCategory == 'Expedited') {
          text = '加急'
        } else {
          text = '优先'
        }
        return text
      }

      const orderMoney = () => {
        let feeList = data.submitInfo?.getFulfillmentPreviewResult?.feeList || []
        let money = 0
        feeList.forEach((e: any) => {
          let num = parseFloat(e?.amount?.value || 0)
          money += num
        })
        return money
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        pre,
        next,
        getImage,
        submit,
        getMarkplaceName,
        enumSpeed,
        orderMoney,
      }
    },
  })
</script>

<style lang="less" scoped>
  .title {
    width: 100%;
    height: 30px;
    line-height: 30px;
    display: flex;
    background-color: #f6f7f9;
    .title-item {
      width: 50%;
      text-align: center;
      cursor: pointer;
    }

    .first {
      background-color: #3166f5;
      color: white;
      position: relative;
      &::before {
        position: absolute;
        right: -15px;
        top: 0;
        display: inline-block;
        content: '';
        width: 0;
        height: 0;
        border-left: 15px solid #3166f5;
        border-top: 15px solid transparent;
        border-bottom: 15px solid transparent;
      }
    }

    .second {
      background-color: #3166f5;
      color: white;
      position: relative;
      &::before {
        position: absolute;
        left: 0;
        top: 0;
        display: inline-block;
        content: '';
        width: 0;
        height: 0;
        border-left: 15px solid #f6f7f9;
        border-top: 15px solid transparent;
        border-bottom: 15px solid transparent;
      }
    }

    .active {
    }
  }

  .item-con {
    width: 100%;
    .item {
      width: 100%;
      margin: 5px 0;
      .clearfix {
        width: 50%;
        .label-text {
          width: 100px;
          text-align: right;
        }

        .label-value {
          font-size: 10px;
          width: calc(100% - 100px);
        }
      }
    }
  }

  .table {
    width: 100%;
  }
</style>
